/**
 * Created with JetBrains WebStorm.
 * User: Joseph
 * Date: 23/04/12
 * Time: 1:22 PM
 * To change this template use File | Settings | File Templates.
 */

function render() {
    console.log('startrender');
    if (!state_ || !metadata_ || !participants_) {
        console.log('quitrender');
        return;
    }
    var x = null;
    fr_key = 'fullrender' + getUserHangoutId();
    r_key = 'render' + getUserHangoutId();

    if (state_[fr_key]) {
        x = parseInt(state_[fr_key]);
    } else {
        x = 1;
        saveValue(fr_key, '1');
    }
    console.log('fullrender: ' + x + ' and ' + last_fullrender);
    if (last_fullrender != x) {
        last_fullrender = x;
        ani_full_render();
    }
    last_fullrender = x;

    if (state_[r_key] != undefined) {
        x = parseInt(state_[r_key]);
    } else {
        x = 1;
        saveValue(r_key, '1');
    }
    console.log('render: ' + x + ' and ' + last_render);
    if (last_render != x) {
        last_render = x;
        ani_render();
    }
    last_render = x;
}


function ani_render() {

    //find and sort change requests
    var max_timestamp = 0;
    var change_keys = new Array;
    for (var key in state_) {
        if (key.substr(0, 7) == '_change') {
            var temp = {};
            temp.key = key;
            temp.timestamp = metadata_[key].timestamp;

            if (temp.timestamp > max_timestamp) {
                max_timestamp = temp.timestamp;
            }
            temp.event_order = parseInt(JSON.parse(state_[key]).event_order);

            change_keys.push(temp);
        }
    }
    var sortFunc = function (a, b) {
        var x = b.event_order - a.event_order;
        if (x == 0) {
            x = a.timestamp - b.timestamp
        }
        return x;
    };
    console.log('Number of change requests: ' + change_keys.length)


    change_keys.sort(sortFunc);
    var pieces_changed = new Array;
    var keep_completed_change = new Array;

    for (var i = 0, iLen = change_keys.length; i < iLen; ++i) {
        var key = change_keys[i].key;
        var change = JSON.parse(state_[key]);
        if (change.piece) {
            if (jQuery.inArray(change.piece, pieces_changed) < 0) {
                pieces_changed.push(change.piece);
                var temp = {};
                temp[change.piece] = state_['_temp' + change.piece];
                var x = (1 + parseInt(change.event_order));
                temp['_event_order' + change.piece] = x.toString();
                saveValue(temp);
                choose_animation(change, key);
            }
        } else {
            if (change.item) {
                choose_animation(change, key);
            }
        }

        //delete old requests
        console.log((max_timestamp - change_keys[i].timestamp));
        if ((max_timestamp - change_keys[i].timestamp) > 1000) {
            removeValue(key);
        }


        for (var j = 0, jLen = completed_change.length; j < jLen; ++j) {
            if (completed_change[j] == key) {
                keep_completed_change.push(key);
            }
        }


    }
    completed_change = keep_completed_change;

}


function choose_animation(change, key) {
    for (var i = 0, iLen = completed_change.length; i < iLen; ++i) {
        if (completed_change[i] == key) {
            console.log('return')
            return
        }
    }

    switch (change.item) {
        case 'rolldice':
            ani_rolldice(change.piece, change.result);
            break;
        case 'move':
            ani_move(change.piece, change.x, change.y);
            break;
        case 'flipcoin':
            ani_move(change.piece, change.result);
            break;
    }
    completed_change.push(key);
}

function ani_full_render() {
    console.log('fullrender');
    var container_div = $('<div />');
    container_div.append(render_pieces(), render_board());
    $('#table').empty()
        .append(container_div);
    full_render = false;
}


function render_pieces() {
    var pieces_div = $('<div />');
    var IMAGE;
    for (var key in state_) {


        if (key.substr(0, 6) == '_piece') {

            var temp = JSON.parse(state_[key]);

            IMAGE = $('<img />')
                .attr({
                    'src':temp.img,
                    'class':'piece',
                    'id':key
                })
                .css('width', temp.width)
                .css('height', temp.height)
                .css('position', 'absolute')
                .css('left', temp.x)
                .css('top', temp.y)
                .draggable({
                    stop:function () {
                        act_move(this.id)
                    }
                }
            )

            if (key.substr(6, 5) == '_dice') {
                IMAGE.dblclick(function () {
                    act_rolldice(this.id);
                });
            }

            if (key.substr(6, 5) == '_coin') {
                IMAGE.dblclick(function () {
                    act_flipcoin(this.id);
                });
            }

            pieces_div.append(IMAGE)
        }
    }
    return pieces_div;
}

function render_board() {
    var key = '_board'
    var board_div = $('<div />');
    var IMAGE;
    if (state_[key] != undefined) {

        var temp = JSON.parse(state_[key]);
        IMAGE = $('<img />')
            .attr({
                'src':temp.img,
                'class':'board',
                'id':key
            })
            .css('width', temp.width)
            .css('height', temp.height)
            .css('position', 'absolute')
            .css('left', temp.x)
            .css('top', temp.y)

        board_div.append(IMAGE);
    }
    return board_div;
}